package net.entelijan.config.impl2;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import javax.swing.JComboBox;

import org.springframework.util.ClassUtils;

import net.entelijan.cobean.combobox.DefaultComboBoxInitializer;
import net.entelijan.cobean.core.ICobean;
import net.entelijan.cobean.core.ISingleSelectionListCobean;

public class DefaultComboBoxInitializerBinderFactory extends
		AbstractBinderFactory {

	public DefaultComboBoxInitializerBinderFactory() {
		super();
	}

	@Override
	protected List<List<String>> adjustPathesOfCoreComponent(List<List<String>> pathes) {
		return PathUtil.removeSuffixesIgnoreCase(pathes, "ComboBox", "Box",
				"DropDownBox", "DropDown");
	}

	@Override
	protected ICobean<?> createCobean(IEnhancedComponent coreComp,
			List<IEnhancedComponent> allComps, Class<?> modelPropertyType, Object config) {
		ICobean<?> re = null;
		if (ClassUtils.isAssignable(Enum.class, modelPropertyType)) {
			DefaultComboBoxInitializer<Enum<?>> ini = new DefaultComboBoxInitializer<Enum<?>>();
			ini.setCoComboBox((JComboBox) coreComp.getComponent());
			final ISingleSelectionListCobean<Enum<?>> cobean = ini.initialize();
			List<Enum<?>> enumValues = getEnumValues(modelPropertyType);
			cobean.setValue(enumValues);
			re = cobean;
		}
		return re;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<Enum<?>> getEnumValues(Class<?> modelPropertyType) {
		Class<? extends Enum> propertyType = (Class<? extends Enum>) modelPropertyType;
		EnumSet<?> allOf = EnumSet.allOf(propertyType);
		return new ArrayList(allOf);
	}

	@Override
	protected boolean isCoreComponent(IEnhancedComponent comp) {
		return comp.getComponent() instanceof JComboBox;
	}

	@Override
	protected String getCobeanProperty() {
		return "selectedValue";
	}
}
